package com.imau.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.imau.bean.SysDept;
import com.imau.bean.TreeEntity;
import com.imau.mapper.SysDeptMapper;
import com.imau.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    private SysDeptMapper baseMapper;

    @Override
    public SysDept queryById(String did) {
       return  baseMapper.selectById(did);
    }

    @Override
    public boolean saveDept(SysDept dept) {


        //1. 使用父部门ID查询，父部门祖籍列表。
        //2. 拼接祖籍列表
        SysDept parentDept = baseMapper.selectById(dept.getParentId());
        String ancestors = parentDept.getAncestors();
        dept.setAncestors(ancestors + "," + dept.getParentId());
        int insert = baseMapper.insert(dept);
        return insert > 0;
    }

    @Override
    public boolean editDept(SysDept dept) {
        //数据库祖籍列表字段的维护
        SysDept newParentDept = baseMapper.selectById(dept.getParentId());
        SysDept oldDept = baseMapper.selectById(dept.getDid());

        //判断原有的对象是否有变化
        if (StringUtils.checkValNotNull(newParentDept) && StringUtils.checkValNotNull(oldDept)) {
            SysDept oldParentDept = baseMapper.selectById(oldDept.getParentId());
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDid();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            //更新子节点祖籍列表
            updateDeptChildren(dept.getDid(), newAncestors, oldAncestors);
        }

        //如果是个子节点，本身启用，父节点原先禁用，更改成启用。
        if(dept.getStatus().equals("0") && StringUtils.isNotEmpty(dept.getAncestors()) && !dept.getAncestors().equals("0"))
        {
            //更新父级节点的状态。
            String []deptIds = dept.getAncestors().split(",");
            baseMapper.updateDeptStatusNormal(deptIds);
        }

        int i = baseMapper.updateById(dept);
        return i > 0;
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(String deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = baseMapper.selectChildByParentId(deptId);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            baseMapper.updateDeptChildren(children);
        }
    }

    @Override
    public boolean removeDeptById(String deptId) {

        //1.判断是否有子节点
        //1.1 先查询按照父部门ID查询
        SysDept sysDept = new SysDept();
        sysDept.setParentId(deptId);
        List<SysDept> depts = queryListDept(sysDept);

        if (CollectionUtil.isEmpty(depts)) {
            //2.删除部门信息
            int i = baseMapper.deleteById(deptId);
            return i > 0;

        } else {

            return false;
        }


    }

    @Override
    public List<SysDept> queryListDept(SysDept dept) {

        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(dept.getDeptName()), SysDept::getDeptName, dept.getDeptName());
        wrapper.eq(StringUtils.isNotEmpty(dept.getParentId()), SysDept::getParentId, dept.getParentId());
        wrapper.eq(StringUtils.isNotEmpty(dept.getStatus()), SysDept::getStatus, dept.getStatus());

        List<SysDept> sysDepts = baseMapper.selectList(wrapper);
        return buildDeptTree(sysDepts);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeEntity> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeEntity::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<String> tempList = depts.stream().map(SysDept::getDid).collect(Collectors.toList());
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }


    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotEmpty(n.getParentId()) && n.getParentId().equals(t.getDid())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }
}
